package com.jdrx.sw.sewage.service.common;

import com.jdrx.sw.sewage.task.xxjob.SewageJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@Service
public class PostgreSqlService {
    private static final Logger logger = LoggerFactory.getLogger(SewageJob.class);

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    public Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName(driverClassName);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            logger.error("数据备份出错了", e);
        }
        return conn;
    }

    public void closeConnection(Connection conn, PreparedStatement pstm) {
        if (pstm != null) {
            try {
                pstm.close();
            } catch (SQLException e) {
                logger.error("预编译出错了", e);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                logger.error("数据库连接关闭出错了", e);
            }
        }
    }

    public PreparedStatement prepareStatementSql(String sql, Connection conn) {
        PreparedStatement pstm = null;
        try {
            pstm = conn.prepareStatement(sql);
        } catch (SQLException e) {
            logger.error("获取预编译对象失败", e);
        }
        return pstm;
    }
}
